
	import com.sodimac.util.alerts.alert;
	import com.sodimac.util.commons.DataGridExport;
	import com.sodimac.util.commons.EstadosBPM;
	import com.sodimac.util.commons.UploadPostHelper;
	import com.sodimac.util.commons.UtilString;
	import com.sodimac.util.controls.adgFooter.FooterAdvancedDataGridColumn;
	import com.sodimac.v2s.events.cargarInfoSfpcProdEvent;
	import com.sodimac.v2s.events.grabarPedidoCorpProdEvent;
	import com.sodimac.v2s.model.ComprasModelLocator;
	import com.sodimac.v2s.view.components.BackgroundCellColor;
	import com.sodimac.v2s.view.components.BackgroundCellColorNac;
	import com.sodimac.v2s.view.components.ScreenFormat;
	import com.sodimac.v2s.view.components.cpCheckbox;
	import com.sodimac.v2s.vo.InfoSfpVO;
	
	import mx.binding.utils.ChangeWatcher;
	import mx.collections.ArrayCollection;
	import mx.controls.AdvancedDataGrid;
	import mx.controls.NumericStepper;
	import mx.events.AdvancedDataGridEvent;
	import mx.events.DataGridEventReason;
    	
    
	/* datos de pantalla */    
	[Bindable] public var numericStepperFac:ClassFactory;
	[Bindable] public var screenFormat:ClassFactory;
		  
	[Bindable] public var resumenArr:Array;
	[Bindable] public var paisesArr:Array;
	[Bindable] public var paisesNacArr:Array;
	[Bindable] public var prodCorpData:ArrayCollection;	
	[Bindable] public var prodNacData:ArrayCollection;
	[Bindable] public var infoSfpVo:InfoSfpVO;
	[Bindable] public var paisesNombres:XMLList;
	[Bindable] public var reporteURL: String;
	[Bindable] public var uploadDataURL: String;
//	[Bindable] public var hideCorr: String;						
	    			
	[Bindable] public var codPais: String;
	[Bindable] public var usuarioId: String;
	[Bindable] public var pedidoCorpId: Number;
	[Bindable] public var empresaId: String;
	
	[Bindable] private var prodNacCLData:ArrayCollection = new ArrayCollection();
	[Bindable] private var prodNacCOData:ArrayCollection = new ArrayCollection();
	[Bindable] private var prodNacPEData:ArrayCollection = new ArrayCollection();
	[Bindable] private var prodNacARData:ArrayCollection = new ArrayCollection();
	
	[Bindable] public  var modelo: ComprasModelLocator = ComprasModelLocator.getInstance();
	
	private var prodCorpUpdated:ArrayCollection = new ArrayCollection();
	private var prodNacUpdated:ArrayCollection = new ArrayCollection();
	
	private var paisesPartArray:Array = new Array("CL","CO","PE","AR");   //orden de los paises que pueden participar de una SFPC
	//private var paisesCorreccion:Array = new Array();                //contiene los paises a modificar
	private var prodFormaEnvio:Array = new Array();
		        	    
	private var cwResumen:ChangeWatcher; 
	private var cwDataGridCorp:ChangeWatcher;
	private var cwDataGridNac :ChangeWatcher;
	
	private var cwPreciosUpdNac:ChangeWatcher;  
	private var cwPreciosUpdHom:ChangeWatcher; 
	
	
	
	
	private function onInit():void
	{
		trace("____"+  this.name + " -->  onInit.");
	
		//Escuchar cambios en prod corp 
		cwResumen      = ChangeWatcher.watch(modelo,'resumenDataPro' , onResumenChange);
		cwDataGridCorp = ChangeWatcher.watch(modelo,'prodConjHomData', onProductosChangeCorp);
		cwDataGridNac  = ChangeWatcher.watch(modelo,'prodConjNacData', onProductosChangeNac);
	
	}
	
  	private function onProductosChangeCorp(e:Event):void
	{
		var col:AdvancedDataGridColumn;
        var cols:Array = dg_corp.columns;	
        
	    cwDataGridCorp.unwatch();
	    
	    trace(" ____"+  this.name + " -->  onProductosChangeCorp.");
		
		//ocultar pais
		if ((paisesArr)  && (paisesArr.length>0) )
		{
			//obtener pais
			var hidePaises:Array = new Array();
			hidePaises = paisesPartArray;
			for (var j:int=0;j<paisesArr.length;j++) 
			{
				var cod:String;
				cod = paisesArr[j];
				for (var k:int=0;k<paisesPartArray.length;k++)
				{
					if (paisesPartArray[k] == cod)
						hidePaises.splice(k,1);
				}
			} 
			trace("-------------------------");
			trace(hidePaises);
			
			for (j=0;j<hidePaises.length;j++) 
			{
				var name:String = UtilString.toLowerCase(hidePaises[j]);
 				for (k=0;k<cols.length;k++)  
				{
					 if (String(cols[k].dataField).indexOf(name +"_") != -1)
					 {
					 	 var column:FooterAdvancedDataGridColumn = dg_corp.columns[k];
					 	 column.visible = false;
					 }  
				} 
			}
		} else {
		
			//hide all 
			for (j=0;j<paisesPartArray.length;j++) 
			{
				var name2:String = UtilString.toLowerCase(paisesPartArray[j]);
 				for (k=0;k<cols.length;k++)  
				{
					 if (String(cols[k].dataField).indexOf(name2 +"_") != -1)
					 {
					 	 var column2:FooterAdvancedDataGridColumn = dg_corp.columns[k];
					 	 column2.visible = false;
					 }  
				} 
			}					
		
		
		} 				
		
		//hide forma de envío
		if (hidePaises)
		{
				trace("ocultando paises en forma envio");
				for (var r:int=0;r<hidePaises.length;r++)
				{
		    		var prefijo:String = hidePaises[r];
		    		if (prefijo == "CL"){
		    			gridEnvioCL.height = 0;
		    			gridEnvioCL.visible = false;
		    		} else if (prefijo == "CO"){
		    			gridEnvioCO.height = 0;
		    			gridEnvioCO.visible = false;
		    		} else if (prefijo == "PE"){
		    			gridEnvioPE.height = 0;
		    			gridEnvioPE.visible = false;
		    		}else if (prefijo == "AR"){
		    			gridEnvioAR.height = 0;
		    			gridEnvioAR.visible = false;
		    		} 						
					
				}
		} 				
  		
  		
	} 			


  	private function onResumenChange(e:Event):void
	{
  		var omitidos:Number = 0;
  		var eliminados:Number = 0;
  		var pos:int = 0;
  		var j:int = 0;		  				  				  
  				  				    
	    cwResumen.unwatch();

  		//update resumenArr, se suman "Omitidos" (7) con "Eliminados" (6)
		for (j=0;j<resumenArr.length;j++) 
		{
			
			if (resumenArr[j]["id"] == 7) //omitidos
			{
				omitidos = resumenArr[j]["cantidad"];
				pos=j;
			}	
		}
		resumenArr.splice(pos,1);
		
		for (j=0;j<resumenArr.length;j++) 
		{
			
			if (resumenArr[j]["id"] == 6)  //eliminados
			{
				eliminados = resumenArr[j]["cantidad"] + omitidos;
				pos=j;
			}	
		}
		resumenArr.splice(pos,1);				
		
  		 
        dg_res.dataProvider.addItem(
            {
                "glosa": "Productos eliminados / omitidos",
                "cantidad": eliminados
            }
         );
         
         
         //cambia tamaño a tabla resumen
         resizeResDatagrid();
  		
	} 	

	
	private function onProductosChangeNac(e:Event):void
	{
		
	    trace("____"+  this.name + " -->  onProductosChangeNac.");
	    cwDataGridNac.unwatch();
	    
	    
	    //asign array for countries and visibility
	    if ((prodNacData)  && (paisesNacArr.length >0))
	    {
	    	trace("asignando arreglos por pais....");
	    
	    	for (var j:int=0;j<paisesNacArr.length;j++) 
	    	{
	    		var prefix:String = paisesNacArr[j];
	    		if (prefix == "CL")
	    		{
	    			prodNacCLData = prodNacData[j];
	    		} else if (prefix == "CO")
	    		{
	    			prodNacCOData = prodNacData[j];
	    		} else if (prefix == "PE")
	    		{
	    			prodNacPEData = prodNacData[j];
	    		}else if (prefix == "AR")
	    		{
	    			prodNacARData = prodNacData[j];
	    		} 
	    	} 
	    }				
	   	
		
		// hide countries compra individual
		if ((paisesNacArr)  && (paisesNacArr.length>0) )
		{
			
			//obtener pais
			var hidePaises:Array = new Array();
			hidePaises = paisesPartArray;
			for (var n:int=0;n<paisesNacArr.length;n++) 
			{
				var cod:String;
				cod = paisesNacArr[n];
				for (var k:int=0;k<paisesPartArray.length;k++)
				{
					if (paisesPartArray[k] == cod)
						hidePaises.splice(k,1);
				}
			}
			trace("hide nac " +  hidePaises);
			
			for (k=0;k<hidePaises.length;k++) 
			{
	    		var pref:String = hidePaises[k];
	    		if (pref == "CL")
	    		{
	    			vboxCL.visible=false;
	    			vboxCL.height=5;
	    		} 
	    		else if (pref == "CO")
	    		{
	    			vboxCO.visible=false;
	    			vboxCO.height=5;
	    		} else if (pref == "PE")
	    		{
	    			vboxPE.visible=false;
	    			vboxPE.height=5;
	    		} else if (pref == "AR")
	    		{
	    			vboxAR.visible=false;
	    			vboxAR.height=5;
	    		}
	    									
			}
		}	
	}
	
	

	private function modificaTotalesConj(event:AdvancedDataGridEvent):void
	{
		
		trace(" ____"+  this.name + " -->  modificaTotalesConj.");
		var columnIndex:int = event.columnIndex;		 
		var cantidad:Number = 0;
		var prefix:String   = "";
		var subPrice:Number = 0;
		var subKgs:Number   = 0;
		var subCbm:Number   = 0;
		var total:Number    = 0;				

		if ( columnIndex != 50)   //omitir
		{	
			cantidad = NumericStepper(event.currentTarget.itemEditorInstance).value;
			prefix   = dg_corp.columns[event.columnIndex].dataField;			
			prefix = prefix.substr(0,3);
			
			subPrice = Number(prodCorpData[event.rowIndex]["unit_price"]);
			subKgs   = Number(prodCorpData[event.rowIndex]["unit_kgs"]);
			subCbm   = Number(prodCorpData[event.rowIndex]["unit_cbm"]);
			 
			if (prefix == "sub")
			{
				
				//update totales all countries
				for (var j:int=0;j<paisesArr.length;j++) 
				{
					prefix = UtilString.toLowerCase(paisesArr[j]);
					if (!isNaN(prodCorpData[event.rowIndex][prefix + "_quantity"]))
					{
						cantidad =  Number(prodCorpData[event.rowIndex][prefix + "_quantity"]);
						
	 					prodCorpData[event.rowIndex][prefix + "_sub_price"] = (cantidad==0)? "0": Number(cantidad * subPrice).toFixed(2);
						prodCorpData[event.rowIndex][prefix + "_sub_kgs"]   = (cantidad==0)? "0": Number(cantidad * subKgs).toFixed(2);
						prodCorpData[event.rowIndex][prefix + "_sub_cbm"]   = (cantidad==0)? "0": Number(cantidad * subCbm).toFixed(2);
						
						/*
						//2010-02-23 - Modificado por RGA - 
						//Se agrega condicion para NO solicitar correccion cuando Proveedor informa que no hay diferencias
						if ( hideCorr != "true")
						{							
							checkRequiereCorreccion(UtilString.toUpperCase(prefix), cantidad, event.rowIndex);
						}
						*/														
						
					}
				}					
				
			} 
			else
			{ 
				//update subs
	 			prodCorpData[event.rowIndex][prefix + "sub_price"] = (cantidad==0)? "0": Number(cantidad * subPrice).toFixed(2);
				prodCorpData[event.rowIndex][prefix + "sub_kgs"]   = (cantidad==0)? "0": Number(cantidad * subKgs).toFixed(2);
				prodCorpData[event.rowIndex][prefix + "sub_cbm"]   = (cantidad==0)? "0": Number(cantidad * subCbm).toFixed(2);
				
				//sum all countries
				for (var t:int=0;t<paisesArr.length;t++) 
				{
					prefix = UtilString.toLowerCase(paisesArr[t]);
					if (!isNaN(prodCorpData[event.rowIndex][prefix + "_quantity"]))
					{
						total +=  Number(prodCorpData[event.rowIndex][prefix + "_quantity"]);
					}
				}
				
				prodCorpData[event.rowIndex]["sub_quantity"] = (Number(total*100)/100);
				prodCorpData[event.rowIndex]["sub_total"] = (Number(total*subPrice*100)/100);
			}	
		}
		 
	}
	
	

	private function validaCantidadCorp(event:AdvancedDataGridEvent):void
	{
		var oldValor:Number = event.currentTarget.editedItemRenderer.data[event.dataField];
		var columnName:String = event.dataField;
		var newValor:Number = 0;
		var caseName:String = "";
		var prefix:String = "";
		var pais:String = "";
		var prefijo_pais:String ="";
		var casePack:Number = 0; 
		var resto:Number = 0;
		var row:Number = 0; 
		var qty:Number = 0;
		var subQty:Number = 0;
		var newQty:Number = 0;
		var sumVendor:Number = 0;
		var proposed:Boolean= false;	
		var unitPrice:Number = 0;			
		
        
		if ( (columnName != "estadoProd") && (oldValor != -1) )
		{	
			
			newValor = NumericStepper(event.currentTarget.itemEditorInstance).value;
			caseName = event.dataField;
			prefix   = caseName.substr(0,3);
			pais     = UtilString.toUpperCase(prefix.substr(0,2));			
			
	        if ( (newValor == oldValor)  || (event.reason == DataGridEventReason.CANCELLED)) {
	            return; 
	        }			
						
			if  (oldValor == 0)  // && (UtilString.equalsIgnoreCase(prodCorpData[event.rowIndex]["problem_name"],"eliminado"))) 
			{
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				event.preventDefault();								
				alert.warning("No es posible modificar la cantidad a productos que han sido eliminados u omitidos.");
				return;
			}                
		
			subQty =  oldValor;
			if ( prefix == "sub" )
			{
				//distribuir diferencia
				trace("editando Sub Quantity ...");
				if ( (paisesArr) && (paisesArr.length) && (subQty > 0)) {

						//calculo mayor  y menor
						for (var k:int=0; k < paisesArr.length;k++)
						{
							qty = 0;
							casePack = 0;
							resto = 0;
							newQty = 0;
							
							prefijo_pais = UtilString.toLowerCase(paisesArr[k]) + "_";
							casePack = Number(prodCorpData[event.rowIndex][prefijo_pais + "case_pack"]);									
							qty =  Number(prodCorpData[event.rowIndex][prefijo_pais + "quantity"]);
						
							if ( (qty) &&  paisesArr[k] == "CL"){
								
								newQty = Math.round( (newValor* ((qty*100/subQty)/100)) );
								resto = newQty%casePack;
								if ( resto != 0)
								{
									proposed= true;
									newQty = Math.ceil(newQty/casePack)*casePack;
								}
								sumVendor += (newQty);
								prodCorpData[event.rowIndex]["cl_quantity"] = (newQty);
							
				    		} else if ((qty) && paisesArr[k]  == "CO"){
	
								newQty = Math.round( (newValor* ((qty*100/subQty)/100)) );
								resto = newQty%casePack;
								if ( resto != 0)
								{
									proposed= true;
									newQty = Math.ceil(newQty/casePack)*casePack;
								}
								sumVendor += (newQty);
								prodCorpData[event.rowIndex]["co_quantity"] = (newQty);			    			
				    			
				    		} else if ((qty) && paisesArr[k]  == "PE"){
								newQty = Math.round( (newValor* ((qty*100/subQty)/100)) );
								resto = newQty%casePack;
								if ( resto != 0)
								{
									proposed= true;
									newQty = Math.ceil(newQty/casePack)*casePack;
								}
								sumVendor += (newQty);
								prodCorpData[event.rowIndex]["pe_quantity"] = (newQty);			    			
				    			
				    		} else if ((qty) && paisesArr[k]  == "AR"){
								newQty = Math.round( (newValor* ((qty*100/subQty)/100)) );
								resto = newQty%casePack;
								if ( resto != 0)
								{
									proposed= true;
									newQty = Math.ceil(newQty/casePack)*casePack;
								}
								sumVendor += (newQty);
								prodCorpData[event.rowIndex]["ar_quantity"] = (newQty);		    			
				    			
				    		} 
						}

					//update col sub_total = qty * unit_price
					unitPrice = Number(prodCorpData[event.rowIndex]["unit_price"]);
					prodCorpData[event.rowIndex]["sub_total"]  = Number(sumVendor * unitPrice);
							
					NumericStepper(event.currentTarget.itemEditorInstance).value = sumVendor;
					event.currentTarget.editedItemRenderer.data[event.dataField] = -1;
					if (proposed)
					{
						alert.info("Se propone una cantidad superior a la ingresada, la cual ha sido distribuída entre los países participantes.");
					} else {
						alert.info("La cantidad ingresada ha sido distribuída entre los países participantes.");
					}							

				} else if (subQty  == 0)
				{
					sumVendor = newValor;
					prodCorpData[event.rowIndex][ UtilString.toLowerCase(paisesArr[0]) + "_quantity"]  = newValor;					
					
					//update col sub_total = qty * unit_price
					unitPrice = Number(prodCorpData[event.rowIndex]["unit_price"]);
					prodCorpData[event.rowIndex]["sub_total"]  = Number(sumVendor * unitPrice);
					event.currentTarget.editedItemRenderer.data[event.dataField] = -1;						
				
				}					
				

			} 
			else
			{
			
				//define case-pack related
				caseName = prefix + "case_pack";
				casePack = Number(prodCorpData[event.rowIndex][caseName]);
				

				if ( isNaN(casePack) || (casePack ==0)) 
				{
					AdvancedDataGrid(event.currentTarget).destroyItemEditor();
					event.preventDefault();
					alert.error("Case Pack no válido, no es posible validar cantidad  ingresada.");
				} 
				else 
				{
					
					var max:Number = NumericStepper(event.currentTarget.itemEditorInstance).maximum;
					if (newValor == max)
					{
						AdvancedDataGrid(event.currentTarget).destroyItemEditor();
						event.preventDefault();								
						alert.warning("Valor ingresado es igual o superior al máximo permitido ("+ pesosFmt.format(max) +").");
					}
					else
					{						
					
						resto=newValor%casePack;
						if (resto !=0)
						{
							newValor = 	Math.ceil(newValor/casePack)*casePack;
							NumericStepper(event.currentTarget.itemEditorInstance).value = newValor;
							event.currentTarget.editedItemRenderer.data[event.dataField] = -1;		
							alert.warning("La cantidad ingresada debe ser múltiplo del case pack ("+ casePack + ").  Se propone una cantidad superior válida.");
						}
	/*
						//2010-02-23 - Modificado por RGA - 
						//Se agrega condicion para NO solicitar correccion cuando Proveedor informa que no hay diferencias
						if ( hideCorr != "true")
						{
							checkRequiereCorreccion(pais, newValor, event.rowIndex);
						}	
						//2010-01-28 - Modificado por RGA  (Corrige problema al chequear correción)							 
						else 
						{
							
							//si cambio es mayor que la tolerancia, habilitar label "Requiere Correccion"
							checkRequiereCorreccion(pais, newValor, event.rowIndex);
							
						}
	*/								
						
					}	
				}
			}
		}	
	}

/*
    private function checkRequiereCorreccion(pais:String, newValor:Number, row:Number):void 
    {
		var valorTol:Number = 0;
		var valorQty:Number = 0;
		var prefix:String = UtilString.toLowerCase(pais) + "_";
		var encendido:Boolean = false;
		
		valorTol = prodCorpData[row][prefix + "max_tolerancia"];
		
		
		if (newValor > valorTol)						
		{
				if (pais == "CL")
				{
					cl_group.headerText = "on";
				}
				else if (pais == "CO")
				{
					co_group.headerText = "on";
				}						
				else if (pais == "PE")
				{
					pe_group.headerText = "on";
				}
				else if (pais == "AR")
				{
					ar_group.headerText = "on";
				}
			
			//inserta en arreglo	
			if (paisesCorreccion.indexOf(pais) < 0)
			{
				paisesCorreccion.push(pais);
			}
			
			//(cambio RG 19.10.2009)  
			//En caso mostrar "Requiere Confirmación" se debe bloquear boton guardar 
			btnGuardar.enabled = false;						
			
        }
        else
        {
			//verifico si corresponde mantener encendido label
			encendido = false;		        
        	for (var j:int=0;j<prodCorpData.length;j++) 
			{
				if (j != row)
				{
					valorTol = isNaN(prodCorpData[j][prefix + "max_tolerancia"])? 0: Number(prodCorpData[j][prefix + "max_tolerancia"]);
					valorQty = isNaN(prodCorpData[j][prefix + "quantity"])? 0: Number(prodCorpData[j][prefix + "quantity"]);
					
					if (valorQty > valorTol)
					{
						encendido = true;
						break;
					}
				} 
			}
			
			if (!encendido)
			{
				if (pais == "CL")
				{
					cl_group.headerText = "off";
				}
				else if (pais == "CO")
				{
					co_group.headerText = "off";
				}						
				else if (pais == "PE")
				{
					pe_group.headerText = "off";
				}
				else if (pais == "AR")
				{
					ar_group.headerText = "off";
				}

				
				//remove form array	
				for (var k:int=0;k<paisesCorreccion.length;k++)
				{
					if (paisesCorreccion[k] == pais)
						paisesCorreccion.splice(k,1);
				}							
					
			}		        
        
    	}
    	
    	if (paisesCorreccion.length == 0)
    	{
    		btnGuardar.enabled = true;
    	}
    }
    */

	
	
	
    private function onCreationCompleteDGCorp():void 
    {
        trace("____"+  this.name + " -->  onCreationCompleteDGCorp.");
        
		var col:AdvancedDataGridColumn;
        var cols:Array = dg_corp.columns; 
        var i:int =0;    
		
		numericStepperFac = new ClassFactory(NumericStepper);
        numericStepperFac.properties = {minimum:0, maximum:999999999, maxChars:9};
        
		screenFormat = new ClassFactory(ScreenFormat);
        
        while (i < cols.length)
        {
        	//para todas las columnas
        	col= cols[i];
        	col.editable = false;

        	//color problem
        	if  (i==0) 
        	{
   				col.itemRenderer = new ClassFactory(BackgroundCellColor);
        	}

            //renderiza NumericStepper
        	if ( (i==10) || (i==18)  || (i==27) || (i==36) || (i==45)) 
        	{
            	col.editable = true;
            	col.editorDataField = "value";
            	col.itemEditor = numericStepperFac;
        	}
        	
        	//render formato
			if ( (i==12) || (i==13) || ((i>=20) && (i<=22)) || ((i>=29) && (i<=31)) || ((i>=38) && (i<=40)) || ((i>=47) && (i<=49))) 
			{
				screenFormat.properties = {fieldName:  col.dataField}
				col.itemRenderer = screenFormat; 
			}
			
			//render checkbox
			if (i == 50)
			{
				col.editable = true;
				col.rendererIsEditor= true; 
				col.editorDataField = "selected";
				col.itemRenderer =  new ClassFactory(cpCheckbox);
			}
						
			
        	i++;
        }
        
     }
     
     
	private function modificaTotalesNac(event:AdvancedDataGridEvent, paisArr:ArrayCollection):void
	{
		var columnIndex:int = event.columnIndex;
		var cantidad:Number = 0;
		var subPrice:Number = 0;
		var subKgs:Number   = 0;
		var subCbm:Number   = 0;
		var total:Number    = 0;
		
		if (columnIndex != 17)  //omitir
		{
			cantidad = paisArr.getItemAt(event.rowIndex).paisQuantity;
			
			subPrice = Number(paisArr[event.rowIndex]["unitPrice"]);
			subKgs   = Number(paisArr[event.rowIndex]["unitKgs"]);
			subCbm   = Number(paisArr[event.rowIndex]["unitCbm"]);
	
			// Get the name of the column being editted.
			paisArr.getItemAt(event.rowIndex).subPrice = (cantidad==0)? "0": Number(cantidad * subPrice).toFixed(2);
			paisArr.getItemAt(event.rowIndex).subKgs =   (cantidad==0)? "0": Number(cantidad * subKgs).toFixed(2);
			paisArr.getItemAt(event.rowIndex).subCbm =   (cantidad==0)? "0": Number(cantidad * subCbm).toFixed(2);
		}		
		
	} 	         

	private function validaCantidadNac(event:AdvancedDataGridEvent):void
	{
		var columnName:String = event.dataField;
		var newValor:Number = 0;
		var oldValor:Number = 0;
		var casePack:Number = 0;
		var resto:Number = 0;	
		
		if (columnName == "paisQuantity")
		{		
		
			oldValor = event.currentTarget.editedItemRenderer.data[event.dataField];	
			if (oldValor == -1){
				return;
			}
			
			newValor = NumericStepper(event.currentTarget.itemEditorInstance).value;
			casePack = Number(event.currentTarget.editedItemRenderer.data["casePack"]);		

			if (oldValor == 0)
			{
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				event.preventDefault();								
				alert.warning("No es posible modificar items eliminados.");
				return;
			} 

			if ( isNaN(casePack) || (casePack ==0)) 
			{
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				event.preventDefault();
				alert.error("Case Pack no válido, no es posible validar cantidad  ingresada.");
			} 
			else 
			{
				var max:Number = NumericStepper(event.currentTarget.itemEditorInstance).maximum;
				if (newValor == max)
				{
					AdvancedDataGrid(event.currentTarget).destroyItemEditor();
					event.preventDefault();	
					alert.warning("Valor ingresado es igual o superior al máximo permitido ("+ pesosFmt.format(max) +").");
				}
				else
				{					
					resto=newValor%casePack;
					if (resto !=0)
					{
						NumericStepper(event.currentTarget.itemEditorInstance).value = 	Math.ceil(newValor/casePack)*casePack;
						event.currentTarget.editedItemRenderer.data[event.dataField] = -1;
						alert.warning("La cantidad ingresada debe ser múltiplo del case pack ("+ casePack + "). Se propone una cantidad superior válida.");
					} 

				}	
			}
		}
		
			
			

	}
	


 	private function onCreationCompleteDGNac(adg:AdvancedDataGrid):void {
		var i:int = 0;
		var col:AdvancedDataGridColumn;
		var cols:Array = adg.columns;
		
		trace("____"+  this.name + " -->  onCreationCompleteDGNac"); 
		numericStepperFac = new ClassFactory(NumericStepper);
		numericStepperFac.properties = {minimum:0, maximum:999999999, maxChars:9};
		
		screenFormat = new ClassFactory(ScreenFormat);
		
		while (i < cols.length)
		{
			//para todos
			col= cols[i];
			col.editable = false;

        	//color problem
        	if  (i==0) 
        	{
   				col.itemRenderer = new ClassFactory(BackgroundCellColorNac);
        	}

			//renderiza NumericStepper
			if (i==8)
			{
				col.editable = true;
				col.editorDataField = "value";
				col.itemEditor = numericStepperFac;
			}
			
			//render formato
			if  ((i==6) || ((i>=11) && (i<=16)))
			{
				screenFormat.properties = {fieldName:  col.dataField};
				col.itemRenderer = screenFormat; 
			}
			
			//render checkbox
			if (i==17)
			{
				col.editable = true;
				col.rendererIsEditor= true; 
				col.editorDataField = "selected";
				col.itemRenderer =  new ClassFactory(cpCheckbox);
			}				
			
			i++;
		}
	} 

     
    public function textFunction(col:AdvancedDataGridColumn):String
	{
		var txt:String = ""; 
		if ((col.headerText =="Subtotal Vendor Proposed Quantity") || (col.headerText =="Case Pack") || (col.headerText =="CP"))
		{
			txt="Total";
		}
		return txt;
	}
	
	
	public function sumFunctionCorp(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodCorpData != null)
		{
			for (var i:int = 0; i < prodCorpData.length; i++)
			{
				if (!isNaN(prodCorpData[i][col.dataField]))
				{
					sum += Number(prodCorpData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	public function sumFunctionNacCL(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodNacCLData != null)
		{
			for (var i:int = 0; i < prodNacCLData.length; i++)
			{
				if (!isNaN(prodNacCLData[i][col.dataField]))
				{
					sum += Number(prodNacCLData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	public function sumFunctionNacCO(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodNacCOData != null)
		{
			for (var i:int = 0; i < prodNacCOData.length; i++)
			{
				if (!isNaN(prodNacCOData[i][col.dataField]))
				{
					sum += Number(prodNacCOData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	public function sumFunctionNacPE(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodNacPEData != null)
		{
			for (var i:int = 0; i < prodNacPEData.length; i++)
			{
				if (!isNaN(prodNacPEData[i][col.dataField]))
				{
					sum += Number(prodNacPEData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	public function sumFunctionNacAR(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodNacARData != null)
		{
			for (var i:int = 0; i < prodNacARData.length; i++)
			{
				if (!isNaN(prodNacARData[i][col.dataField]))
				{
					sum += Number(prodNacARData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	
	//styleFunction="setColorStyle" (for ADG)
     public function setColorSubQuantity(data:Object, col:AdvancedDataGridColumn):Object
     {
         if(data["sub_quantity"] <= 0)
             return {color:0xFF0000};
         else    
 			return {color:0x0000FF};
 
         return null;
     }  		

     public function setColorPaisQuantity(data:Object, col:AdvancedDataGridColumn):Object
     {
         if(data["paisQuantity"] <= 0)
             return {color:0xFF0000};
         else    
 			return {color:0x0000FF};
 
         return null;
     } 


     public function setColorPaisCorpQuantity(data:Object, col:AdvancedDataGridColumn):Object
     {
   		var monto:Number = 0;
   		
   		if (data["cl_quantity"] != null){
   			monto = data["cl_quantity"];
   		} else if (data["co_quantity"] != null){
   			monto = data["co_quantity"];
   		} else if (data["pe_quantity"] != null){
   			monto = data["pe_quantity"];
   		} else if (data["ar_quantity"] != null){
   			monto = data["ar_quantity"];
   		}
   		
         if(monto <= 0)
             return {color:0xFF0000};
         else    
 			return {color:0x0000FF};
 
         return null;
     } 	
     
	private function resizeResDatagrid():void
	{
		dg_res.height = dg_res.measureHeightOfItems(0, resumenArr.length) + dg_res.headerHeight+6;
	}
			
	private function actualizarPrecios():void
	{
		trace("____"+  this.name + " -->  actualizarPrecios.");
		
     	//re-llamada a los servicios	       
   		var prodNacEvent:cargarInfoSfpcProdEvent = new cargarInfoSfpcProdEvent(); // interno llama a prod corp
		prodNacEvent.metodo = "consultaPedidoCorpProductoPaisPrice";
		prodNacEvent.idEmpresa = empresaId;
		prodNacEvent.idPedidoCorp = pedidoCorpId;
		prodNacEvent.dispatch(); 
		
		cwPreciosUpdNac = ChangeWatcher.watch(ComprasModelLocator.getInstance(),'prodConjNacPrice',getNewPricesNac);  
		cwPreciosUpdHom = ChangeWatcher.watch(ComprasModelLocator.getInstance(),'prodConjHomPrice',getNewPricesHom);
		
	}	         



	private function getNewPricesNac(e:Event):void
	{
		trace("____"+  this.name + " -->  getNewPricesNac.");
		
		var prodNacPrice:ArrayCollection = new ArrayCollection();
		var initProdNac:Boolean = false;
		prodNacPrice = modelo.prodConjNacPrice;
		cwPreciosUpdNac.unwatch();
		
		//check if datagrid exist
		if (prodNacCLData.length >0)
		{
			initProdNac = true;
		}
		if (prodNacCOData.length >0)
		{
			initProdNac = true;
		}
		if (prodNacPEData.length >0)
		{
			initProdNac = true;
		}
		if (prodNacARData.length >0)
		{
			initProdNac = true;
		}
		
		if (!initProdNac)
		{
			onProductosChangeNac(e);
		}
		
						
		//update prices nac
		var pre:String ="";
		var sku:String ="";
		var price:Number = 0;
		for (var q:int = 0; q < prodNacPrice.length; q++)
		{
			pre = prodNacPrice[q]["idPais"];
			sku = prodNacPrice[q]["sku"];
			price = prodNacPrice[q]["unitPrice"];
    		if (pre == "CL")
    		{
    			
				var idProdCL:String = "";
				for (var k:int=0;k<prodNacCLData.length;k++)
				{
					idProdCL = prodNacCLData[k]["sku"];
					if (sku == idProdCL)
					{
						prodNacCLData[k]["unitPrice"] = price;
						prodNacCLData[k]["subPrice"] =   Number(prodNacCLData[k]["paisQuantity"]) * price;
						break;
					}

				}		    			
    			 
    		} else if (pre == "CO")
    		{
    			 
				var idProdCO:String = ""; 
				for (var k2:int=0;k2<prodNacCOData.length;k2++)
				{
					idProdCO = prodNacCOData[k2]["sku"];
					if (sku == idProdCO)
					{
						prodNacCOData[k2]["unitPrice"] = price;
						prodNacCOData[k2]["subPrice"] =   Number(prodNacCOData[k2]["paisQuantity"]) * price;
						break;
					}

				}			    			
    			
    		} else if (pre == "PE")
    		{
    			
				var idProdPE:String = "";
				for (var k3:int=0;k3<prodNacPEData.length;k3++)
				{
					idProdPE = prodNacPEData[k3]["sku"];
					if (sku == idProdPE)
					{
						prodNacPEData[k3]["unitPrice"] = price;
						prodNacPEData[k3]["subPrice"] =   Number(prodNacPEData[k3]["paisQuantity"]) * price;
						break;
					}

				}			    			
    			
    		}else if (pre == "AR")
    		{
    			 
				var idProdAR:String = "";
				for (var k4:int=0;k4<prodNacARData.length;k4++)
				{
					idProdAR = prodNacARData[k4]["sku"];
					if (sku == idProdAR)
					{
						prodNacARData[k4]["unitPrice"] = price;
						prodNacARData[k4]["subPrice"] =   Number(prodNacARData[k4]["paisQuantity"]) * price;
						break;
					}

				}			    			
    		} 					
			
		}				
		
		//update datagrids				
		if (prodNacCLData.length >0)
		{
			dg_cl.dataProvider = prodNacCLData;
		}
		if (prodNacCOData.length >0)
		{
			dg_co.dataProvider = prodNacCOData;
		}
		if (prodNacPEData.length >0)
		{
			dg_pe.dataProvider = prodNacPEData;
		}
		if (prodNacARData.length >0)
		{
			dg_ar.dataProvider = prodNacARData;
		}
		
	}


	private function getNewPricesHom(e:Event):void
	{
		trace("____"+  this.name + " -->  getNewPricesHom.");
		
		var prodHomPrice:ArrayCollection = new ArrayCollection();
		prodHomPrice = modelo.prodConjHomPrice;
		
		cwPreciosUpdHom.unwatch();
		
		//update prices hom
		var idProd:Number = 0;
		var newVal:Number = 0;
		for (var i:int = 0; i < prodHomPrice.length; i++)
		{
			idProd = prodHomPrice[i]["vin"];
			newVal = prodHomPrice[i]["unit_price"];
			
			var producto:Number = 0;
			for (var h:int = 0; h < prodCorpData.length; h++)
			{
				producto = prodCorpData[h]["vin"];
				if (producto == idProd)
				{
					prodCorpData[h]["unit_price"] = newVal;
					prodCorpData[h]["sub_total"] = Number(prodCorpData[h]["sub_quantity"]) * newVal; 
					
					//revisa paises
					var pref_pais:String ="";
					var precio_pais:Number = 0;
					for (var k:int=0;k<paisesArr.length;k++)
					{
						pref_pais = UtilString.toLowerCase(paisesArr[k]);
						precio_pais = Number(prodHomPrice[i][pref_pais + "_price_initial"]);
						if (!isNaN(prodHomPrice[i][pref_pais + "_price_initial"]))
						{
							prodCorpData[h][pref_pais + "_price_initial"] = precio_pais;
							prodCorpData[h][pref_pais + "_sub_price"] = Number(prodCorpData[h][pref_pais + "_quantity"]) * precio_pais;
						}
					}
					
					break;
				}
			}					
		}
			
		//update datagrid
		dg_corp.dataProvider = prodCorpData;
		
		alert.info("Los precios han sido actualizados exitosamente!.");				
		
	}


     
	private function getProductosModificados():void
	{
		var newValor:Number = 0;
		var oriValor:Number = 0;
		var newOmitido:Boolean = false;
		var oriOmitido:Boolean = false; 

		//get productos corp updated
		for (var i:int = 0; i < prodCorpData.length; i++)
		{
			newValor = prodCorpData[i]["sub_quantity"];
			oriValor = prodCorpData[i]["sub_quantity_original"];
			newOmitido = prodCorpData[i]["estadoProd"];
			oriOmitido = prodCorpData[i]["original_estadoProd"];			
			
			if ( ( newValor != oriValor ) || (newOmitido != oriOmitido) )
			{
				var objProd:Object = new Object();
				objProd.vin = prodCorpData[i]["vin"];
				objProd.precio_final = prodCorpData[i]["sub_total"];
				objProd.sub_quantity = newValor;
				objProd.id_problema = prodCorpData[i]["id"];
				objProd.moq = prodCorpData[i]["moq"];
				objProd.omitido = (newOmitido)? "S":"N";   //nuevo
				
				var paises:Array = new Array();
				for (var q:int = 0; q < paisesArr.length; q++)
				{
					var prefix:String =  UtilString.toLowerCase(paisesArr[q]) + "_";
					if (!isNaN(prodCorpData[i][prefix + "quantity"]))
					{
						var prod:Object = new Object();
						prod.pais = UtilString.toUpperCase(prefix.substr(0,2));
						prod.sku = prodCorpData[i][prefix + "sku"];
						prod.cantidad = prodCorpData[i][prefix + "quantity"];
						prod.precio = prodCorpData[i][prefix + "sub_price"];
						
						paises.push(prod);
					}
					
				}
				objProd.paises = paises;
				prodCorpUpdated.addItem(objProd);

	  		}
	  		
		}
		
		
		//get prod nacionales
		
		//get productos CL
		for (i=0; i < prodNacCLData.length; i++)
		{
			newValor = prodNacCLData[i]["paisQuantity"];
			oriValor = prodNacCLData[i]["paisQuantityOriginal"];
			newOmitido = prodNacCLData[i]["estadoProd"];
			oriOmitido = prodNacCLData[i]["original_estadoProd"];
										
			if ( ( newValor != oriValor ) || (newOmitido != oriOmitido) )
			{
				var objProd1:Object = new Object();
				objProd1.idPais = "CL";
				objProd1.sku = prodNacCLData[i]["sku"];
	    		objProd1.cantidad = newValor
	    		objProd1.precio = prodNacCLData[i]["subPrice"];
	    		objProd1.idProblema = prodNacCLData[i]["idProblem"];
	    		objProd1.omitido = (newOmitido)? "S":"N";   //nuevo
	    		prodNacUpdated.addItem(objProd1);						
			}
		}				
		
		//get productos CO
		for (i=0; i < prodNacCOData.length; i++)
		{
			newValor = prodNacCOData[i]["paisQuantity"];
			oriValor = prodNacCOData[i]["paisQuantityOriginal"];
			newOmitido = prodNacCOData[i]["estadoProd"];
			oriOmitido = prodNacCOData[i]["original_estadoProd"];
										
			if ( ( newValor != oriValor ) || (newOmitido != oriOmitido) )
			{
				var objProd2:Object = new Object();
				objProd2.idPais = "CO";
				objProd2.sku = prodNacCOData[i]["sku"];
	    		objProd2.cantidad = newValor
	    		objProd2.precio = prodNacCOData[i]["subPrice"];
	    		objProd2.idProblema = prodNacCOData[i]["idProblem"];
	    		objProd2.omitido = (newOmitido)? "S":"N";   //nuevo
	    		prodNacUpdated.addItem(objProd2);						
			}
		}			
	
		//get productos PE
		for (i=0; i < prodNacPEData.length; i++)
		{
			newValor = prodNacPEData[i]["paisQuantity"];
			oriValor = prodNacPEData[i]["paisQuantityOriginal"];
			newOmitido = prodNacPEData[i]["estadoProd"];
			oriOmitido = prodNacPEData[i]["original_estadoProd"];
			
			if ( ( newValor != oriValor ) || (newOmitido != oriOmitido) )
			{
				var objProd3:Object = new Object();
				objProd3.idPais = "PE";
				objProd3.sku = prodNacPEData[i]["sku"];
	    		objProd3.cantidad = newValor
	    		objProd3.precio = prodNacPEData[i]["subPrice"];
	    		objProd3.idProblema = prodNacPEData[i]["idProblem"];
	    		objProd3.omitido = (newOmitido)? "S":"N";   //nuevo
	    		prodNacUpdated.addItem(objProd3);						
			}
		}				

		//get productos AR
		for (i=0; i < prodNacARData.length; i++)
		{
			newValor = prodNacARData[i]["paisQuantity"];
			oriValor = prodNacARData[i]["paisQuantityOriginal"];
			newOmitido = prodNacARData[i]["estadoProd"];
			oriOmitido = prodNacARData[i]["original_estadoProd"];
											
			if ( (newValor != oriValor ) || (newOmitido != oriOmitido) )
			{
				var objProd4:Object = new Object();
				objProd4.idPais = "AR";
				objProd4.sku = prodNacARData[i]["sku"];
	    		objProd4.cantidad = newValor
	    		objProd4.precio = prodNacARData[i]["subPrice"];
	    		objProd4.idProblema = prodNacARData[i]["idProblem"];
	    		objProd4.omitido = (newOmitido)? "S":"N";   //nuevo
	    		prodNacUpdated.addItem(objProd4);						
			}
		}	
	
			
	}	


	private function getFormaEnvio():void 
	{
		
		trace(" ____"+  this.name + " -->  getFormaEnvio.");
		if (paisesArr)
		{
			
			//get values
			for (var x:int=0;x<paisesArr.length;x++) 
			{
		    		var pref:String = paisesArr[x];
	    			var objFE:Object = new Object();
		    		if (pref == "CL"){
		    			objFE.pais = pref;
		    			objFE.valor = rbgrp_envioCL.selectedValue.toString();
		    			prodFormaEnvio.push(objFE);
		    		} else if (pref == "CO"){
		    			objFE.pais = pref;
		    			objFE.valor = rbgrp_envioCO.selectedValue.toString();
		    			prodFormaEnvio.push(objFE);
		    		} else if (pref == "PE"){
		    			objFE.pais = pref;
		    			objFE.valor = rbgrp_envioPE.selectedValue.toString();
		    			prodFormaEnvio.push(objFE);
		    		} else if (pref == "AR"){
		    			objFE.pais = pref;
		    			objFE.valor = rbgrp_envioAR.selectedValue.toString();
		    			prodFormaEnvio.push(objFE);
		    		} 						
			}
		}
	}


	private function simulaFormaEnvio():void 
	{
		
		if (paisesArr)
		{
			
			//get values
			for (var x:int=0;x<paisesArr.length;x++) 
			{
		    		var pref:String = paisesArr[x];
	    			var objFE:Object = new Object();
		    		if (pref == "CL"){
		    			objFE.pais = pref;
		    			objFE.valor = "LCL";
		    			prodFormaEnvio.push(objFE);
		    		} else if (pref == "CO"){
		    			objFE.pais = pref;
		    			objFE.valor = "LCL";
		    			prodFormaEnvio.push(objFE);
		    		} else if (pref == "PE"){
		    			objFE.pais = pref;
		    			objFE.valor = "LCL";
		    			prodFormaEnvio.push(objFE);
		    		} else if (pref == "AR"){
		    			objFE.pais = pref;
		    			objFE.valor = "LCL";
		    			prodFormaEnvio.push(objFE);
		    		} 						
			}
		}
	}


	private function checkFormaEnvio():void 
	{
		var marcados:Boolean = true;
		var lista:String = "";
		
		trace(" ____"+  this.name + " -->  checkFormaEnvio.");
		
		if (paisesArr)
		{
			
			//check selected
			for (var x:int=0;x<paisesArr.length;x++) 
			{
		    	var pref:String = paisesArr[x];
	    		if (pref == "CL"){
	    			if (!rbgrp_envioCL.selectedValue){
	    				marcados = false;
	    				lista += XML(paisesNombres).pais.(@codIata == pref).@nombre  + "\n";
	    			}
	    		} else if (pref == "CO"){
	    			if (!rbgrp_envioCO.selectedValue){
	    				marcados = false;
	    				lista += XML(paisesNombres).pais.(@codIata == pref).@nombre + "\n";
	    			}
	    		} else if (pref == "PE"){
	    			if (!rbgrp_envioPE.selectedValue){
	    				marcados = false;
	    				lista += XML(paisesNombres).pais.(@codIata == pref).@nombre + "\n"; 
	    			}
	    		} else if (pref == "AR"){
	    			if (!rbgrp_envioAR.selectedValue){
	    				marcados = false;
	    				lista += XML(paisesNombres).pais.(@codIata == pref).@nombre + "\n"; 
	    			}
	    		} 
			}
		}
		
		
		if (!marcados)
		{
			alert.warning("Falta indicar la forma de envío para: \n"  + lista);
		} 
		else
		{
			getFormaEnvio();
			//checkPaisesCorreccionEnviar();
			onClickBtnEnviar();
		
		}
		
		
	}						

/*			
	private function checkPaisesCorreccionEnviar():void 
	{

		trace(" ____"+  this.name + " -->  checkPaisesCorreccionEnviar.");
		if (paisesCorreccion.length > 0 )
		{

			//show msg paises participantes
			var lista:String = "";
			for (var i:int=0; i<paisesCorreccion.length; i++)
			{
				lista +=  XML(paisesNombres).pais.(@codIata == paisesCorreccion[i]).@nombre + "\n";
			}
			
			alert.info("Se enviará una solicitud de corrección a los siguientes paises:\n" + lista, onClickBtnEnviar);
		} else {
		
			onClickBtnEnviar(new CloseEvent("cerrar"));
		}

		
	}	
	*/	         
     
	public function onClickBtnEnviar():void
	{	
		var savePedidoEvt:grabarPedidoCorpProdEvent = new grabarPedidoCorpProdEvent();
		var version:Number = new Number(infoSfpVo.version);
		
		trace(" ____"+  this.name + " -->  onClickBtnEnviar.");
		
		//obtener productos modificados
		getProductosModificados();
		
 		savePedidoEvt.idPedidoCorp = pedidoCorpId;
		savePedidoEvt.idEmpresa = empresaId;
		savePedidoEvt.idProveedor = infoSfpVo.proveedorId;
		savePedidoEvt.version =((version - Math.floor(version))>0)? Math.ceil(version) + ".0":(version+1) + ".0";

		savePedidoEvt.estado = EstadosBPM.ENVIO;

		//				if (paisesCorreccion.length > 0 )
		//				{
		//					savePedidoEvt.estado = EstadosBPM.CORREGIR;
		//				} 
		//				else
		//				{
		//					savePedidoEvt.estado = EstadosBPM.ENVIO;
		//				}				

		if (prodCorpUpdated.length > 0 ) 
		{
			savePedidoEvt.productosCorpArr = prodCorpUpdated;  //listado de prod. modificados
		}	
		
		if (prodNacUpdated.length > 0 )
		{
			savePedidoEvt.productosNacArr = prodNacUpdated;  //listado de prod. nac modificados
		}	

		//				if (paisesCorreccion.length > 0 )
		//				{
		//					savePedidoEvt.paisesCorreccionArr = paisesCorreccion;  //listado de paises con solic correccion
		//				}
		
		if (prodFormaEnvio.length > 0 )
		{
			savePedidoEvt.paisesFormaEnvioArr = prodFormaEnvio;  //listado de forma de envio por pais
		}				

		savePedidoEvt.dispatch();
		btnEnviar.enabled = false;
      	btnGuardar.enabled = false;												

	}
	
	
  			
	public function onClickBtnGuardar():void
	{	
		
		var savePedidoEvt:grabarPedidoCorpProdEvent = new grabarPedidoCorpProdEvent();
		var new_version:Number = new Number(infoSfpVo.version);
		
		trace(" ____"+  this.name + " -->  onClickBtnGuardar.");
		
		//obtener productos modificados
		getProductosModificados();
		
		//simula Forma Envio (no se guarda, pero servicio lo requiere)
		simulaFormaEnvio();				
		
		new_version += Number(0.1);
 		savePedidoEvt.idPedidoCorp = pedidoCorpId;
		savePedidoEvt.idEmpresa = empresaId;
		savePedidoEvt.idProveedor = infoSfpVo.proveedorId;
		savePedidoEvt.estado = EstadosBPM.GUARDA;
		savePedidoEvt.version = new_version.toFixed(1);

		if (prodCorpUpdated.length > 0 ) 
		{
			savePedidoEvt.productosCorpArr = prodCorpUpdated;  //listado de prod. modificados
		}	
		
		if (prodNacUpdated.length > 0 )
		{
			savePedidoEvt.productosNacArr = prodNacUpdated;  //listado de prod. modificados
		}	
		
		if (prodFormaEnvio.length > 0 )
		{
			savePedidoEvt.paisesFormaEnvioArr = prodFormaEnvio;  //listado de forma de envio por pais
		}					
		
		savePedidoEvt.dispatch();
		btnGuardar.enabled = false;
      	btnEnviar.enabled = false;
	}		
  			
  			
        private function generarReporte(formato:String):void 
        {
            
            var url:String;
            var sourceCorp:String =""; 
            var sourceNac:String = "";
            
            if (dg_corp) {
            	sourceCorp = DataGridExport.exportCSV(dg_corp, "Corporativos");
            }
            if (paisesNacArr) {
            	
            	for (var k:int=0;k<paisesNacArr.length;k++)
				{
		    		var prefijo:String = paisesNacArr[k];
					//trace("pais envio: " + prefijo);
		    		if (prefijo == "CL")
		    		{
		    			sourceNac  += DataGridExport.exportCSV(dg_cl, "CHILE") + "|";
		    		} else if (prefijo == "CO")
		    		{
		    			sourceNac  += DataGridExport.exportCSV(dg_co, "COLOMBIA") + "|";
		    		} else if (prefijo == "PE")
		    		{
		    			sourceNac  += DataGridExport.exportCSV(dg_pe, "PERU") + "|";
		    		} else if (prefijo == "AR")
		    		{
		    			sourceNac  += DataGridExport.exportCSV(dg_ar, "ARGENTINA") + "|";
		    		}
				}

            		
            }
            
            //remove last separator
            if (sourceNac.charAt(sourceNac.length-1) == '|')
            {
            	sourceNac = sourceNac.substring(0, sourceNac.length-1);
            }	
			
			//send data for report
			UploadPostHelper.uploadDataReport( 'ig9.txt', uploadDataURL, sourceCorp);
			UploadPostHelper.uploadDataReport( 'sub_ig9.txt', uploadDataURL, sourceNac);

			
		    //call report					
			//					var variables:URLVariables = new URLVariables();
			//					variables.pNumeroSFP = infoSfpVo.numeroSFP;
			//					variables.pEstado = infoSfpVo.estado; 
			//					variables.pFecha = infoSfpVo.fecha_formato;
			//					variables.pProveedor = infoSfpVo.proveedorNombre + '  ( ' + infoSfpVo.proveedorId + ' )';
			//					variables.pVersion = infoSfpVo.version;
			//					variables.pIntMerchant = infoSfpVo.merchantNombre; 
			//					variables.formato = formato;
			//					variables.fileName ='ig9.txt';			            
			
            var request:URLRequest = new URLRequest();
			request.url = reporteURL + "?formato="+ formato +
						"&fileName=ig9.txt"+
						"&pNumeroSFP="+ infoSfpVo.numeroSFP +
						"&pEstado="+ infoSfpVo.estado + 
						"&pFecha="+ infoSfpVo.fecha_formato +
						"&pProveedor="+ infoSfpVo.proveedorNombre + " ( " + infoSfpVo.proveedorId + " )" +
						"&pVersion="+ infoSfpVo.version +
						"&pIntMerchant="+ infoSfpVo.merchantNombre;
			request.method = URLRequestMethod.POST;
			//request.data = variables;
            navigateToURL(request, '_blank');						
			
        }	
        
